package cn.ilikes.tools.nosql.jpa.configs.envs.sys;

import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.JPASQLRunTimeException;
import cn.ilikes.tools.nosql.jpa.JPASQLSystemEnv;
import cn.ilikes.tools.nosql.jpa.configs.JPASQLConfigurationPaserException;
import cn.ilikes.tools.nosql.jpa.configs.JPASQLPersistenceUnitMetadata;
import cn.ilikes.tools.nosql.jpa.configs.PersistenceXMLLoader;

/**
 * 解析persistence file
 * 
 * @author fack
 * 
 */
public class PersistenceUnitConfigsPaser {

	private static Logger logger = Loggerfactory.instance(PersistenceUnitConfigsPaser.class);

	PersistenceXMLLoader persistenceXMLLoader = new PersistenceXMLLoader();

	@SuppressWarnings("unused")
	private Properties properties;

	private Map<String, JPASQLPersistenceUnitMetadata> result;

	public PersistenceUnitConfigsPaser(JPASQLSystemEnv systemEnv, String persistenceUnitFile, Properties properties) {
		super();
		this.properties = properties;
		Loggerfactory.info(logger, "Persistence Unit  Paser  Configs init success ! ");
		config(systemEnv, persistenceUnitFile);
	}

	private void setResult(Map<String, JPASQLPersistenceUnitMetadata> result) {
		this.result = result;
	}

	@SuppressWarnings("unused")
	private void setProperties(Properties properties) {
		this.properties = properties;
	}

	private void config(JPASQLSystemEnv systemEnv, String persistenceUnitFile) {
		if (!systemEnv.isIssysinit())
			throw new JPASQLRunTimeException("JPA SQL System Env Not Init ..................");
		try {
			Map<String, JPASQLPersistenceUnitMetadata> result = persistenceXMLLoader.paserPersistenceMetadatas(persistenceUnitFile);
			setResult(result);
		} catch (JPASQLConfigurationPaserException e) {
			Loggerfactory.error(logger, e);
			throw new JPASQLRunTimeException(e);
		}
	}

	public JPASQLPersistenceUnitMetadata selectJPASQLPersistenceUnitMetadata(String persistenceUnitName) {
		return result.get(persistenceUnitName);
	}

}
